import re
import Interpreter

ANSIEscape = "\x1b[%sm"
ANSIReset  = ANSIEscape % "0"

types = {
    'bold'      : '1',
    'light'     : '2',
    'underline' : '4',
    'invert'    : '7',
}

colors = {
    'reset'   : '0',
    'black'   : '30',
    'red'     : '31',
    'green'   : '32',
    'yellow'  : '33',
    'blue'    : '34',
    'magenta' : '35',
    'cyan'    : '36',
    'white'   : '37',
}

rTypes  = "(?<=,)" + "|(?<=,)".join(types.keys())
rColors = "|".join(colors.keys())
regexp = re.compile("\${("+ rColors +"),?("+ rTypes +")?}")

# need to think about the regexp 
def colorize(text):
  """
  Replaces ${color,type} with appropriate color codes
  """
  return "%s%s%s" % (ANSIReset, re.sub(regexp,regexpRepl,text), ANSIReset)

def regexpRepl(match):
  "Regular expression substitute function"
  mColor, mType =  match.groups()
  colorString = ""
  typenum = ''
  if mType:
    typenum = types.get(mType, '') + ";"
  colornum = colors.get(mColor, '0')

  return ANSIEscape % (typenum+colornum)

@Interpreter.command("color")
def color_command(ch,args):
  """
  Usage:
  color

  Displays a list of available colors
  """
  buf = []
  buf.append("${blue,bold}Available colors:${reset}")
  for color in colors:
    buf.append(colorize("%-8s ${%s}%8s${reset} ${%s,bold}Bold" % (color, color, color, color)))
  ch.to_self("\n".join(buf))
